/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller;

import com.apache.client.LogClient;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.common.XmlWhiteUtils;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * description:  setvlet父类
 *
 * @author Hou Dayu 创建时间：2016-8-22
 */
@SuppressWarnings("serial")
public abstract class BaseHttpServlet extends BaseAction {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //super.doPost(request, response);
        String path = request.getServletPath();
        String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
        if (StrUtil.isNotNull(cookieValue)) {
            this.setLoginUser(request);
        }
        boolean mark = unlockPath(path);//自名单验证
        if (!mark) {
            LoginUser loginUser = this.getSessionUser(request);
            if (null == loginUser) {//判断当前用户是否已登录
                String basePath = getAppUrl(request);
                String url = ConfigUtil.getInstance().getValueByKey("login_url") + basePath;
                response.sendRedirect(url); //跳到登录页面
                return;
            }
        }
        doInvoke(request, response);
    }

    private boolean unlockPath(String path) {
        Map<String, ArrayList<String>> whiteMap = new HashMap<String, ArrayList<String>>();
        XmlWhiteUtils.getInstance().deWhiteXml(whiteMap, "portal");
        ArrayList whiteUrl = (ArrayList) whiteMap.get("whiteUrl");
        ArrayList whiteParadigm = (ArrayList) whiteMap.get("whiteParadigm");
        int wp = whiteParadigm.size();
        if (path.length() > 1) {
            if (whiteUrl.contains(path)) {
                return true;
            }
            for (int i = 0; i < wp; i++) {
                if (((String) whiteParadigm.get(i)).contains("*")) {
                    String wdir = ((String) whiteParadigm.get(i)).replace("*", "");
                    int s = path.indexOf(wdir);
                    if (s == 0) {
                        return true;
                    }
                } else if (!"".equals(whiteParadigm.get(i))) {
                    int s = path.indexOf((String) whiteParadigm.get(i));
                    if (s == 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * description:  添加审记信息
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected void addLogInfo(String logType, String className, String userEname, Map map) {
        Map<String, Object> logMap = new HashMap<String, Object>();
        logMap.put("logType", logType);
        logMap.put("logClassName", className);
        logMap.put("logIp", PortalPubFactory.getLocalIp());
        logMap.put("log_userEname", userEname);
        logMap.putAll(map);
        LogClient.getInstance().execute(logMap);//添加日志
    }

    protected LoginUser getSessionUser(HttpServletRequest request) {
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        return loginUser;
    }

    protected String getAppUrl(HttpServletRequest request) {
        String path1 = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request
                .getServerPort() + path1 + request.getServletPath();
        String appUrl = "?appUrl=" + basePath;
        return appUrl;
    }

    /**
     * description:  获取请求参数
     */
    @SuppressWarnings("rawtypes")
    protected Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Set keSet = request.getParameterMap().entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }
            if (value.length > 0) {
                if (StrUtil.isNotNull(value[0])) {
                    map.put(ok.toString(), value[0]);
                    request.setAttribute(ok.toString(), value[0]);
                }
            }
        }
        return map;
    }

    /**
     * 输出json数据
     *
     * @param json
     * @param response
     */
    protected void outputJson(String json, HttpServletResponse response) throws IOException {
        if (StrUtil.isNotNull(json)) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();
            out.close();
        }
    }
}
